package Demo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class HttpClient {
    private Socket socket = null;

    public HttpClient(String serverIP, int serverPort) throws IOException {
        socket = new Socket(serverIP, serverPort);
    }

    public void get(String url) {
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()) {
            StringBuilder httpRequest = new StringBuilder();
            httpRequest.append("GET" + url + "http/1.1\n");
            httpRequest.append("Host:" + socket.getInetAddress().getHostName() + ":" + socket.getPort() + "\n");
            httpRequest.append("\n");

            outputStream.write(httpRequest.toString().getBytes());
            outputStream.flush();

            byte[] buffer = new byte[1024 + 1024];
            int bytesRead = inputStream.read(buffer);
            String httpResponse = new String(buffer, 0, bytesRead);
            System.out.println(httpResponse);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void post(String url, String body) {
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()) {
            StringBuilder httpRequest = new StringBuilder();
            httpRequest.append("Post" + url + "http/1.1\n");
            httpRequest.append("Host:" + socket.getInetAddress().getHostName() + ":" + socket.getPort() + "\n");
            httpRequest.append("Content-Length:" + body.getBytes().length + "\n");
            httpRequest.append("Content-Type: text/plain\n");

            httpRequest.append("\n");
            httpRequest.append(body);

            outputStream.write(httpRequest.toString().getBytes());
            outputStream.flush();

            byte[] buffer = new byte[1024 + 1024];
            int bytesRead = inputStream.read(buffer);
            String httpResponse = new String(buffer, 0, bytesRead);
            System.out.println(httpResponse);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws IOException {
        HttpClient client = new HttpClient("localhost", 8080);
        client.get("/index.html");
        client.post("/login", "username=admin&password=admin");
    }
}
